package com.zhangdi.zddemo.zookeeper;

import org.apache.zookeeper.AddWatchMode;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

public class ZKCreate {
    public static ZooKeeper zk;
    private static ZKConnection conn;

    public static void create(String path, byte[] data) {
        try {
            zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String path = "/zhangdi/log";

        byte[] data = "{\"name\":\"log\", \"url\":\"192.168.10.5\", \"port:\":[1880, 1881]}".getBytes();

        conn = new ZKConnection();
        try {
            zk = conn.connector("192.168.145.128:2181,192.168.145.128:2182,192.168.145.128:2183");
//            Stat stat = zk.exists("/zhangdi", false);
//            if(stat == null){
//                byte[] parentNodeInfo = "{\"name\":\"server\"}".getBytes();
//                create("/zhangdi", parentNodeInfo);
//            }
//            create(path, data);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
//            conn.close();
        }

        try {
            while (true) {
                synchronized (zk) {
                    zk.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        try {
//            conn.latch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
